package com.iRomantic.controller.company;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.activation.FileTypeMap;
import javax.imageio.ImageIO;
import net.coobird.thumbnailator.Thumbnails;

import sun.security.util.BigInt;

import com.iRomantic.common.BaseController;
import com.iRomantic.common.oss.OSSService;
import com.iRomantic.common.util.Email;
import com.iRomantic.common.util.FileUtil;
import com.iRomantic.common.util.UuidUtil;
import com.iRomantic.config.Constant;
import com.iRomantic.domain.entity.Client;
import com.iRomantic.domain.entity.Enterprise;
import com.iRomantic.domain.entity.HotelPicture;
import com.iRomantic.domain.entity.Invitation;
import com.iRomantic.domain.entity.Member;
import com.iRomantic.domain.entity.Picture;
import com.iRomantic.domain.entity.Video;
import com.iRomantic.domain.entity.Wedding;
import com.jfinal.upload.UploadFile;
import com.mysql.jdbc.StringUtils;

public class CompanyController extends BaseController {
 
	
	public void index(){
		this.renderWebJsp("company/index.jsp");
	}
	/**
	 * by kaiguang
	 */
	/*
	 * 登录
	 */
	public void login(){
		String name = this.getPara("name");
		String psd = this.getPara("passWord");
		System.out.println(name+"--"+psd);
		
		Member member = Member.Dao.findFirst("select * from t_member where loginName=?",name);
		
		if(member==null||!psd.equals(member.get("password"))){
			System.out.println("登录失败！");
			this.setAttr("msg", "登录失败！");
			this.renderWebJsp("company/index.jsp");
			
		}else{
			System.out.println("登录成功！");
			this.setAttr("msg", "登录成功！");
			System.out.println(member.toJson());
			this.setSessionAttr("USER", member);
			this.homePage();
			member.set("lastLoginTime", new Date().toLocaleString()).update();
			this.renderWebJsp("company/businessHomePage.jsp");
		}		
	
	}
	/*
	 * 退出
	 */
	public void logout(){
		this.removeSessionAttr("USER");
		this.renderWebJsp("company/index.jsp");
	}
	
	/*
	 * 注册
	 */	
	public void regist(){
		String memberId = UuidUtil.getUuid();		//生成登录表的主键					
		this.createMember(memberId);		
		this.renderWebJsp("company/index.jsp");
	}
	/*
	 *修改密码
	 */
	public void changePass(){		
		Member member = this.getSessionAttr("USER");
		String pass = member.get("password");
		
		String oldPass = this.getPara("oldPass");
		String newPass = this.getPara("newPass");
		String surePass = this.getPara("surePass");
		if(pass.equals(oldPass)&&newPass.equals(surePass)){
			String id =  member.getStr("id");
			Member.Dao.findById(id).set("password", newPass).update();
			member.set("password", newPass);
			this.setSessionAttr("USER", member);			
			member = this.getSessionAttr("USER");		
			this.renderWebJsp("company/businessHomePage.jsp");
			
		}
		else{
			this.setAttr("msg", "输入密码有错误");
			this.renderWebJsp("company/changePass.jsp");
		}
			
		
	}
	/*
	 * 发送修改密码的邮件链接
	 */
	public void sendEmailLink() {
		String emailAddress = this.getPara("emailAddress");
		String pass = this.getPara("passWord");
		if("".equals(emailAddress)||"".equals(pass)||emailAddress==null||pass==null){
			System.out.println("hao");
			this.setAttr("msg", "邮箱或密码不能为空");
			goFogetPass();
		}
//		Member member = Member.Dao.findFirst("select * from t_member where email=?", emailAddress);
//		if(member==null)this.renderWebJsp("company/fogetPass.jsp");
//		member.set("password", pass);
			try {
				Email email = new Email();
				email.writeHead("找回密码");
				email.writeContent(pass);
				email.writeTo(emailAddress);
				email.saveMessage();
				email.send();
				this.renderWebJsp("company/index.jsp");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				this.setAttr("msg", "邮箱地址不对");
				this.renderWebJsp("company/fogetPass.jsp");
			}
	}
	/*
	 * 商家認證信息
	 */
	public void certify(){
		String savePath = getSession().getServletContext().getRealPath(Constant.ENTERPRISE_PICTURE);
		UploadFile file1 = this.getFile("businessLicense",savePath);
		UploadFile file2 = this.getFile("idCard",savePath);
		UploadFile file3 = this.getFile("applyLetter",savePath);
		
		String registNo = this.getPara("registNo");
		String address = this.getPara("address");
		String createTime = this.getPara("createTime");
		String businessTerm = this.getPara("businessTerm");
		String idName = this.getPara("idName");
		String idNo = this.getPara("idNo");
		
		System.out.println(registNo+address+createTime+businessTerm+idName+idNo);
		this.setAttr("msg", "成功!");
		this.renderWebJsp("company/businessCertifyPage.jsp");
	}
	
	/*
	 * 跳转
	 */
	public void goRegist(){
		this.renderWebJsp("company/regist.jsp");
	}
	public void goChangePass(){
		this.renderWebJsp("company/changePass.jsp");
	}
	public void goBusinessHomePage(){	
		this.homePage();
		this.renderWebJsp("company/businessHomePage.jsp");
	}
	public void goFogetPass(){
		this.renderWebJsp("company/fogetPass.jsp");
	}
	public void goBusinessCertifyPage(){
		this.renderWebJsp("company/businessCertifyPage.jsp");
	}
	
	/*
	 * 存储用户信息,存储到数据库里面
	 */
	private void createMember(String memberId){ 
		String name=this.getPara("loginName");
		String passWord = this.getPara("password");
		String surePass = this.getPara("surePass");
//		Member member = this.getModel(Member.class);
//		member.set("loginName", name);
//		member.save();
//		System.out.println(name);
		if(passWord.equals(surePass)){
			String enterPriseId = this.createEnterprise();	
			Member member = Member.Dao;		
			member.set("id", memberId);

			member.set("T_E_id", enterPriseId);
			member.set("password", passWord);
			member.set("loginName",name);
			member.save();
		}		
	}
	
	/*
	 * 存储创建公司信息，存储到数据库里面
	 */
	private String createEnterprise(){	
		String name = this.getPara("enterpristName");
		String introduce = this.getPara("info");
		String email = this.getPara("email");
		String phone = this.getPara("phone");
		String address =this.getPara("address");
		String webUrl = this.getPara("webUrl");
		
		Enterprise enterprise = Enterprise.DAO;
		enterprise.set("id", "");
		enterprise.set("name",name);
		enterprise.set("info",introduce);
		enterprise.set("email",email);
		enterprise.set("phone",phone );
		enterprise.set("address",address);
		enterprise.set("webUrl",webUrl);
		enterprise.save();
		
		return enterprise.getStr("id");
		
	}
	/*
	 * 商家主页信息
	 */
	private void homePage(){
		Member member = this.getSessionAttr("USER");
		String t_e_id = member.get("T_E_id");
		System.out.println(t_e_id);
		Enterprise enterprise = Enterprise.DAO;
		enterprise = enterprise.findById(t_e_id);
		
		this.setAttr("companyName", enterprise.get("name"));
		this.setAttr("companyTelNo", enterprise.get("phone"));
		this.setAttr("companyAddress", enterprise.get("address"));
		this.setAttr("companyInfo", enterprise.get("info"));
		this.setAttr("lastTime", member.get("lastLoginTime"));
		this.setAttr("registName", member.get("loginName"));
		
	}
	
	
	/**
	 * -------------------------------------------------------------------------------------
	 * ------------------------------------------------------------------------------------
	 * by wenjun
	 */
	public void ToaddApp()
	{ 
		//这里测试性的假设商家已经登录,并且,给一个假数据
		// Member m=Member.Dao.FindMemberById("11111");
		 //System.out.println(m.getStr("loginName"));
		Enterprise enterprise=new Enterprise();
		enterprise.set("id","34b3deb2-6fb3-4181-91a3-c4b2ccd3c1cc");
		setSessionAttr("USER",enterprise);
		this.renderWebJsp("company/App/AppAdd.jsp");
	}
	
	//第一步
	public void AppAddFirst()
	{
		
		String clientId=getPara("clientId");
		//酒店的id
		String hotelId=getPara("hotelId");
		
		System.out.println(hotelId);
		
		getSession().setAttribute("hotelId",hotelId);
		String wedId=UUID.randomUUID().toString();
		System.out.println("wedId:"+wedId);
		//将app的id保存一下
		getSession().setAttribute("wedId", wedId);
		Wedding wedding=getModel(Wedding.class);
		wedding.set("id",wedId);
		wedding.set("state","-1");
		wedding.set("T_C_id", clientId);
		wedding.set("hotelId",hotelId);
		wedding.save();
		renderJson();
	}
	
	//第二步
	public void AppAddSecond()
	{
		String title=getPara("title");
		int skin=getParaToInt("skin");
		int state=getParaToInt("state");
		String WedId=(String) getSession().getAttribute("wedId");
		getSession().setAttribute("state",state);
		Wedding.DAO.findById(WedId).set("title", title).set("skinType", skin).update();
		renderJson();
	}
	//第三步
	public void AppAddThraid()
	{
		//当用户最后按下生成的时候,把原先设置好的状态添加到数据库表中
		//	否则,该app还是无效的
		int state=(Integer) getSession().getAttribute("state");
		String WedId=(String) getSession().getAttribute("wedId");
		Enterprise enterprise=(Enterprise) getSession().getAttribute("USER");
		
		String binfo=getPara("binfo");
		String bginfo=getPara("bginfo");
		String info=getPara("info");
		
		int i_style=getParaToInt("i_style");
		String i_info=getPara("i_info");
		
		String hotelId=getPara("hotelId");//酒店主键
		BigInteger weddingDate=BigInteger.valueOf(  Long.parseLong(getPara("wdate")));
		Wedding.DAO.findById(WedId)
					.set("brideInfo", binfo)
					.set("bridegroomInfo",bginfo)
					.set("info",info)
					.set("weddingDate", weddingDate)
					.set("state",state)
					.set("number", 12306)   					//app的number 暂时这样
					.set("enterpriseId", enterprise.get("id"))  //商家的id
					.set("hotelId",hotelId)
					.update();
		
		//插入请帖信息
		new Invitation().set("info",i_info).set("style", i_style).set("weddingId",WedId).save();
	}
	
	//婚纱照上传
	public void WedImgUpload() throws Exception
	{
		String WedId=(String) getSession().getAttribute("wedId");
		String savePath = this.getSession().getServletContext().getRealPath(Constant.TEMP_FOLDER);
		  List<UploadFile> ufs=getFiles(savePath);
		  System.out.println("dir:"+ufs.get(0).getSaveDirectory());
		  for(UploadFile uf:ufs)
		  {
			  Picture picture =new Picture();
			  	picture.set("weddingId",WedId );
			  	picture.initAttrByUpload(uf, savePath);
			  	picture.save();
		  }
		
		  renderJson();
		 
	}
	//酒店图片上传
	public void hotelImageUpload() throws Exception
	{
		String hotelId=(String) getSession().getAttribute("hotelId");
		String savePath = this.getSession().getServletContext().getRealPath(Constant.TEMP_FOLDER);
		List<UploadFile> ufs=getFiles(savePath);
		 for(UploadFile picture:ufs)
		  {
			 HotelPicture currPicture = this.getModel(HotelPicture.class);
			 currPicture.set("hotelId", hotelId);			 
			 String pictureName = FileUtil.randomFileName(picture.getFileName());
			 OSSService.getInstance().save(Constant.HOTEL_PICTURE+currPicture.getStr("hotelId")+"/"+pictureName, picture.getFile());
				picture.getFile().delete();
			
				currPicture.set("url", pictureName);
				currPicture.save();
				
		  }
		renderJson();
	}
	
	
	/**
	 * 婚礼视频上传
	 * @param
	 * @throws Exception 
	 * 
	 */
	public void WedVideoUpload()
	{
		String WedId=(String) getSession().getAttribute("wedId");
		String savePath = this.getSession().getServletContext().getRealPath(Constant.TEMP_FOLDER);
		
		UploadFile pic = this.getFile("file",savePath,200*1024*1024);
		String fileName=pic.getFileName();
		String tempName= FileUtil.randomFileName(fileName);
		
		Video video =getModel(Video.class);
		video.set("weddingId",WedId);
		
	
		//上传到云,抛出网络异常
	 try {
		OSSService.getInstance().save(Constant.VIDEO_PICTURE+video.getStr("weddingId")+"/"+tempName, pic.getFile());
	} catch (Exception e) {
		 e.printStackTrace();
		 renderJson("error");
		 return;
	}
		String id=UUID.randomUUID().toString();
		System.out.println(id);
		video.set("id",id);
		video.set("url",tempName);
		
		video.save();
		getSession().setAttribute("id",id);
		
		renderJson("");
		
	}
	/**
	 *婚礼视频缩略图上传
	 * @throws Exception 
	 */
	public void WedVideoImgUpload() 
	{
		
		String id=(String) getSession().getAttribute("id");
		String savePath = this.getSession().getServletContext().getRealPath(Constant.TEMP_FOLDER);
		//保存图片
		UploadFile pic = this.getFile("file",savePath);
		
		System.out.println("id:"+id+"  pic:"+pic.getFileName());
		
		
		Video video = new Video();
		 video=Video.DAO.findById(id);
		 System.out.println("idididid:"+video.getStr("weddingId"));
		 //生成缩略图 
		 File thumbnailsFile = null;
		 
			try {
				thumbnailsFile = CreateImg(pic,savePath);
				OSSService.getInstance().save(Constant.VIDEO_PICTURE+video.getStr("weddingId")+"/"+thumbnailsFile.getName(), pic.getFile());
			} catch (Exception e) {
				e.printStackTrace();
				renderJson("{\"url\":\"error\"}");
			}
			//删除原图
		 pic.getFile().delete();
		 video.set("thumbnailUrl",thumbnailsFile.getName());
		 video.update();
		 System.out.println("videos:"+video.getStr("weddingId"));
		 String url=Constant.OSS_PATH+Constant.VIDEO_PICTURE +video.getStr("weddingId")+"/" +video.get("thumbnailUrl");
		 //String []json=new String[]{Constant.OSS_PATH+Constant.VIDEO_PICTURE +video.getStr("weddingId")+"/" +video.get("thumbnailUrl"),id};
		  String json="{\"url\":\""+url+"\",\"id\":\""+id+"\"}";
		 renderJson(json);
		 
	}

	private File CreateImg(UploadFile pic, String savePath) throws Exception
	{
		String pictureName=FileUtil.randomFileName(pic.getFileName());
		BufferedImage img = ImageIO.read(pic.getFile());
		int width = img.getWidth();
		int height = img.getHeight();
		//生成缩略图
				BufferedImage thumbnail = Thumbnails.of(pic.getFile()).width(300).asBufferedImage();
				String thumbnailsName = "thumbnail_"+pictureName;
				File thumbnailsFile = new File(savePath,thumbnailsName);
				int thumbnailWidth = thumbnail.getWidth();
				int thumbnailHeight = thumbnail.getHeight();
				ImageIO.write(thumbnail, "jpg", thumbnailsFile); 
		 
		return thumbnailsFile;
		
		
	}
	
	 /**
	  * 根据id删除视频
	  * 没有实现将对应的文件删除,目前只删除数据库中对应的行
	  */
	public void DelVideo()
	{
		String videoId=getPara("videoId");
		System.out.println("id:"+videoId);
		Video video=getModel(Video.class);
		video.findById(videoId).delete();
		renderJson();
	}
	
	/**
	 * 得到商家的客户信息
	 */
	public void GetClients()
	{
		Enterprise enterprise=new Enterprise();
		//暂时的数据,应该从session中去取
		enterprise.set("id","34b3deb2-6fb3-4181-91a3-c4b2ccd3c1cc");
		getSession().setAttribute("USER",enterprise);
		String name="";
		String id="";
		List<Client> clients=enterprise.getClients(name, id);
		System.out.println(clients.size());
		setAttr("clients", clients);
		this.renderWebJsp("company/Client/clientShow.jsp");
	}
	
	/**
	 * 添加客户信息
	 */
	public void AddClient()
	{	
		Enterprise enterprise=(Enterprise) getSession().getAttribute("USER");
		Client client=getModel(Client.class);
		client.set("id",UUID.randomUUID().toString());
		client.set("t_c_e",enterprise.get("id"));
		client.save();
		GetClients();
	}
	/**
	 *删除客户信息
	 */
	public void DelClient()
	{
		Enterprise enterprise=(Enterprise) getSession().getAttribute("USER");
		String ids=getPara("ids");
		System.out.println("ids:"+ids);
		String []idarr=ids.split(",");
		for(String id:idarr)
		{
			Client client=getModel(Client.class);
			client.deleteById(id);
		}
		GetClients();
	}
	
	/**
	 *更新客户信息
	 */
	public void Update()
	{
		Client client=getModel(Client.class);
		//client.set("id",UUID.randomUUID().toString());
		client.update();
		GetClients();
	}
	/**
	 *得到某个客户的App
	 */
	public void getClientApps()
	{
		String id=getPara("id");
		//System.out.println("id:"+id);
		 Client client=new Client();
		 	client.set("id",id);
		 	List<Wedding> weddings=client.getApps();
		 	System.out.println("size:"+weddings.size());
		 	renderJson(weddings);
		
	}
	/**
	 *删除APP
	 */
	public void delApp()
	{
		String ids=getPara("ids");
		System.out.println("ids:"+ids);
		String []idarr=ids.split(",");
		for(String id:idarr)
		{
			Wedding app=new Wedding();
			app.set("id",id);
			app.set("state",0);//App的话,设置其状态为0
			app.update();
		}
	}
}
